//
//  DaiBanShiXiangViewController.m
//  JuBoCRM
//
//  Created by iMac on 2024/2/2.
//  Copyright © 2024 iningKe. All rights reserved.
//

#import "DaiBanShiXiangViewController.h"
#import "FSCalendar.h"
#import "DaiBanShiXiangTableViewCell.h"
#import "BRDatePickerView.h"
#import "GenJinJiLuViewController.h"
#import "KeHuXiangQingViewController.h"
#import "NSDate+Helper.h"
@interface DaiBanShiXiangViewController ()<UITableViewDelegate,UITableViewDataSource,FSCalendarDataSource,FSCalendarDelegate,FSCalendarDelegateAppearance,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate> {
    NSArray *courseLiveList;
    //    选中的日期
    NSMutableArray *dateSelectArray;
    //    当前月份
    NSString *currentMonth;
    //    当前年
    NSString *currentYear;
    
    NSString *currentDate;
    
    NSArray *dataSource;
    
    NSString *lastDate;
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;
@property (weak, nonatomic) IBOutlet FSCalendar *calendar;

@property (strong, nonatomic) NSCalendar *gregorian;
@property (strong, nonatomic) NSDateFormatter *dateFormatter2;
@property (weak, nonatomic) IBOutlet TPKeyboardAvoidingTableView *mainTableView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewHeight;


@property (strong, nonatomic) NSArray *datesWithEvent;


@end

@implementation DaiBanShiXiangViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.customNavBar.title = @"待办事项";
    _topSpace.constant = NavaBarHeight;
    
    
    [_mainTableView registerNib:[UINib nibWithNibName:@"DaiBanShiXiangTableViewCell" bundle:nil] forCellReuseIdentifier:@"DaiBanShiXiangTableViewCell"];
    
    //    设置日历控件的代理以及基础属性
    _calendar.dataSource = self;
    _calendar.delegate = self;
    _calendar.scrollEnabled = YES;
    _calendar.allowsMultipleSelection = NO;
    _calendar.allowsSelection = YES;
    _calendar.scrollDirection = FSCalendarScrollDirectionHorizontal;
    _calendar.calendarHeaderView.backgroundColor = [UIColor whiteColor];
    _calendar.appearance.headerMinimumDissolvedAlpha = 0;
    _calendar.calendarWeekdayView.backgroundColor = [UIColor whiteColor];
    _calendar.appearance.todayColor = rgba(40, 120, 255, 1);
    _calendar.appearance.titleTodayColor = rgba(40, 120, 255, 1);

    _calendar.appearance.weekdayTextColor = rgba(24, 27, 37, 1);
    
    _calendar.appearance.headerTitleColor = rgba(24, 27, 37, 1);
    _calendar.appearance.eventSelectionColor = [UIColor clearColor];
    _calendar.appearance.headerSeparatorColor = rgba(223, 223, 223, 1);
    _calendar.today = nil;
    //    [_calendar registerClass:[DIYCalendarCell class] forCellReuseIdentifier:@"cell"];
    
    _calendar.placeholderType = FSCalendarPlaceholderTypeNone;
    _calendar.adjustsBoundingRectWhenChangingMonths = YES;
    
    self.gregorian = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
 
    self.gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    self.dateFormatter2 = [[NSDateFormatter alloc] init];
    self.dateFormatter2.dateFormat = @"yyyy-MM-dd";

    [_calendar registerClass:[FSCalendarCell class] forCellReuseIdentifier:@"cell"];
    
    
    _calendar.appearance.headerDateFormat = @"yyyy-MM";
    
    
    [self getInfoFromServerWithDate:[ZZPUtils getTimeFromShortTimeDa:[NSDate date]] andNeedReload:YES];
    
    
    
}


//获取当天的数据信息
- (void)getInfoFromServerWithDate:(NSString *)date andNeedReload:(BOOL)reload{
    NSString *url = [NSString stringWithFormat:@"/crmBackLog/app/todayAppCustomer?time=%@",date];
    
    
    lastDate = date;
    
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:url andParas:nil andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            NSDictionary *dataDic = [info objectForKey:@"data"];
            if(reload){
                if([[dataDic objectForKey:@"allDate"] isKindOfClass:[NSArray class]]){
                    self.datesWithEvent = [dataDic objectForKey:@"allDate"];
                }else{
                    self.datesWithEvent = [NSArray array];
                }
                

                dispatch_async(dispatch_get_main_queue(), ^{
                   // UI更新代码
                    [self.calendar reloadData];
                });

            }
            
            if([[dataDic objectForKey:@"data"] isKindOfClass:[NSArray class]]){
                dataSource = [dataDic objectForKey:@"data"];
            }else{
                dataSource = [NSArray array];
            }
            
            if(dataSource.count == 0){
                _tableViewHeight.constant = ScreenHeight-NavaBarHeight-392;
            }else{
                if(dataSource.count*38+4 < ScreenHeight-NavaBarHeight-392){
                    _tableViewHeight.constant = dataSource.count*38+4;
                }else{
                    _tableViewHeight.constant = ScreenHeight-NavaBarHeight-392;
                }
            }
            
            
            [_mainTableView reloadData];
        }
    }];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 38;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DaiBanShiXiangTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DaiBanShiXiangTableViewCell"];
    NSDictionary *dataDic = dataSource[indexPath.row];
    
    NSDate *nextTime = [NSDate dateFromString:GetHandleString(dataDic, @"nextTime") withFormat:@"yyyy-MM-dd HH:mm:ss"];
    if([[NSDate date] daysLaterThan:nextTime] == 0){
        if([GetHandleString(dataDic, @"followup") intValue] == 1){
            cell.itemImage.image = LocalImagePath(@"待办事项已跟进");
        }else{
            cell.itemImage.image = LocalImagePath(@"待办事项写跟进");
        }
    }else{
        if([GetHandleString(dataDic, @"followup") intValue] == 1){
            cell.itemImage.image = LocalImagePath(@"待办事项已跟进");
        }else{
            cell.itemImage.image = LocalImagePath(@"待办事项已过期");
        }
    }
    cell.nameLabel.text = GetHandleString(dataDic, @"customerName");
    cell.phoneLabel.text = GetHandleString(dataDic, @"mobile");
    
    cell.userInfoClickBlock = ^{
        KeHuXiangQingViewController *xiangQing = [[KeHuXiangQingViewController alloc] init];
        xiangQing.customerId = GetHandleString(dataDic, @"customerId");
        [self pushViewController:xiangQing];
    };
    
    
    cell.xieJiLuClickBlock = ^{
        NSDate *nextTime = [NSDate dateFromString:GetHandleString(dataDic, @"nextTime") withFormat:@"yyyy-MM-dd HH:mm:ss"];
        if([[NSDate date] daysLaterThan:nextTime] == 0){
            GenJinJiLuViewController *xinJian = [[GenJinJiLuViewController alloc] init];
            xinJian.activityTypeId = GetHandleString(dataSource[indexPath.row], @"customerId");
            xinJian.addSuccessClickBlock = ^{
                [self getInfoFromServerWithDate:lastDate andNeedReload:NO];
            };
            [self pushViewController:xinJian];
        }
//        GenJinJiLuViewController *xinJian = [[GenJinJiLuViewController alloc] init];
//        xinJian.activityTypeId = GetHandleString(dataSource[indexPath.row], @"customerId");
//        xinJian.addSuccessClickBlock = ^{
//            [self getInfoFromServerWithDate:lastDate andNeedReload:NO];
//        };
//        [self pushViewController:xinJian];
    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
//    NSDictionary *dataDic = dataSource[indexPath.row];
//    
//    NSDate *nextTime = [NSDate dateFromString:GetHandleString(dataDic, @"nextTime") withFormat:@"yyyy-MM-dd HH:mm:ss"];
//    if([[NSDate date] isEarlierThanOrEqualTo:nextTime]){
//        GenJinJiLuViewController *xinJian = [[GenJinJiLuViewController alloc] init];
//        xinJian.activityTypeId = GetHandleString(dataSource[indexPath.row], @"customerId");
//        xinJian.addSuccessClickBlock = ^{
//            [self getInfoFromServerWithDate:lastDate andNeedReload:NO];
//        };
//        [self pushViewController:xinJian];
//    }
}


-(UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"暂无需跟进客户"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"暂无需跟进客户~"attributes: @{NSFontAttributeName: [UIFont systemFontOfSize:16],NSForegroundColorAttributeName: rgba(163, 168, 185, 1)}];
    return string;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return YES;
}



#pragma mark - Target actions

#pragma mark - <FSCalendarDataSource>

- (NSInteger)calendar:(FSCalendar *)calendar numberOfEventsForDate:(NSDate *)date
{
    NSString *dateString = [self.dateFormatter2 stringFromDate:date];
    if ([_datesWithEvent containsObject:dateString]) {
        return 1;
    }
    return 0;
}
- (nullable UIColor *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance titleDefaultColorForDate:(NSDate *)date{
    NSString *dateString = [self.dateFormatter2 stringFromDate:date];
    NSString *dateString1 = [self.dateFormatter2 stringFromDate:[NSDate date]];
    NSLog(@"%@====%@",date,[NSDate date]);
    if([dateString isEqualToString:dateString1]){
        return rgba(40, 120, 255, 1);
    }
    return rgba(24, 27, 37, 1);
}
#pragma mark - <FSCalendarDelegateAppearance>
- (nullable NSString *)calendar:(FSCalendar *)calendar subtitleForDate:(NSDate *)date{
    NSString *dateString = [self.dateFormatter2 stringFromDate:date];
    NSString *dateString1 = [self.dateFormatter2 stringFromDate:[NSDate date]];
    NSLog(@"%@====%@",date,[NSDate date]);
    if([dateString isEqualToString:dateString1]){
        return @"今";
    }
    return nil;
}
- (nullable UIColor *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance subtitleDefaultColorForDate:(NSDate *)date{
    NSString *dateString = [self.dateFormatter2 stringFromDate:date];
    NSString *dateString1 = [self.dateFormatter2 stringFromDate:[NSDate date]];
    NSLog(@"%@====%@",date,[NSDate date]);
    if([dateString isEqualToString:dateString1]){
        return rgba(40, 120, 255, 1);
    }
    return [UIColor whiteColor];
}
- (CGPoint)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance subtitleOffsetForDate:(NSDate *)date{
    NSString *dateString = [self.dateFormatter2 stringFromDate:date];
    NSString *dateString1 = [self.dateFormatter2 stringFromDate:[NSDate date]];
    NSLog(@"%@====%@",date,[NSDate date]);
    if([dateString isEqualToString:dateString1]){
        return CGPointMake(0, 5);
    }
    return CGPointMake(0, 0);
}
- (NSArray *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance eventDefaultColorsForDate:(NSDate *)date
{
//    NSString *dateString = [self.dateFormatter2 stringFromDate:date];
//    if ([_datesWithMultipleEvents containsObject:dateString]) {
//        return @[[UIColor magentaColor],appearance.eventDefaultColor,[UIColor blackColor]];
//    }
    return @[rgba(40, 120, 255, 1)];
}

- (UIColor *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance fillSelectionColorForDate:(NSDate *)date
{
//    NSString *key = [self.dateFormatter1 stringFromDate:date];
//    if ([_fillSelectionColors.allKeys containsObject:key]) {
//        return rgba(40, 120, 255, 1);
//    }
    return rgba(40, 120, 255, 1);
}

- (UIColor *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance fillDefaultColorForDate:(NSDate *)date
{
//    NSString *key = [self.dateFormatter1 stringFromDate:date];
//    if ([_fillDefaultColors.allKeys containsObject:key]) {
//        return _fillDefaultColors[key];
//    }
    return [UIColor whiteColor];
}

- (CGFloat)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance borderRadiusForDate:(nonnull NSDate *)date
{

    return 1.0;
}

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
    [self getInfoFromServerWithDate:[ZZPUtils getTimeFromShortTimeDa:date] andNeedReload:NO];
}


//上个月
- (IBAction)before:(UIButton *)sender {
    NSDate *current = self.calendar.currentPage;
    NSDate *previousMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:-1 toDate:current options:0];

    NSLog(@"=====%@",current);
    [self.calendar setCurrentPage:previousMonth animated:YES];
    
    NSDateFormatter *forMate = [[NSDateFormatter alloc] init];
    forMate.dateFormat = @"yyyy-MM";
    
    NSString *date = [forMate stringFromDate:current];
    
    [self getInfoFromServerWithDate:[NSString stringWithFormat:@"%@-01",date] andNeedReload:YES];

//
}
//下个月
- (IBAction)next:(UIButton *)sender {
    NSDate *current = self.calendar.currentPage;
    NSDate *nextMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:1 toDate:current options:0];
    NSDate *nextMonth1 = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:2 toDate:current options:0];
    NSLog(@"=====%@",nextMonth1);
    [self.calendar setCurrentPage:nextMonth animated:YES];

    NSDateFormatter *forMate = [[NSDateFormatter alloc] init];
    forMate.dateFormat = @"yyyy-MM";
    
    NSString *date = [forMate stringFromDate:nextMonth1];
    
    [self getInfoFromServerWithDate:[NSString stringWithFormat:@"%@-01",date] andNeedReload:YES];

}
//筛选时间
- (IBAction)shaiXuanShiJian:(UIButton *)sender {
    // 出生年月日
    BRDatePickerView *datePickerView = [[BRDatePickerView alloc]init];
    datePickerView.pickerMode = BRDatePickerModeYM;
    datePickerView.title = @"";
    datePickerView.minDate = nil;
    datePickerView.maxDate = nil;
    datePickerView.isAutoSelect = NO;

    datePickerView.resultBlock = ^(NSDate *selectDate, NSString *selectValue) {
   
        NSLog(@"selectValue=%@", selectValue);
        NSLog(@"selectDate=%@", selectDate);
        NSLog(@"---------------------------------");
        
     
        [self.calendar setCurrentPage:selectDate animated:YES];
        
        
        [self getInfoFromServerWithDate:[NSString stringWithFormat:@"%@-01",selectValue] andNeedReload:YES];
    };
 
    
    BRPickerStyle *customStyle = [[BRPickerStyle alloc]init];
    customStyle.pickerColor = [UIColor whiteColor];
    customStyle.selectRowTextColor = rgba(51, 51, 51, 1);
    customStyle.titleBarColor = [UIColor whiteColor];
    customStyle.titleTextColor = [UIColor whiteColor];
    customStyle.cancelTextColor = rgba(153, 153, 153, 1);
    customStyle.doneTextColor = rgba(40, 120, 255, 1);
    customStyle.titleBarHeight = 48;
    customStyle.titleTextFont = [UIFont systemFontOfSize:18];
    datePickerView.pickerStyle = customStyle;
    customStyle.topCornerRadius = 10;
    customStyle.hiddenTitleLine = YES;
    customStyle.separatorColor = rgba(223, 229, 242, 1);
    customStyle.separatorHeight = 0.5;
    customStyle.rowHeight = 64;

    [datePickerView show];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
